package com.wxtt.android.realm;

import android.content.Context;
import com.fast.dev.frame.RealmUtils;
import com.fast.dev.frame.utils.DateUtils;
import com.wxtt.android.bean.WxArticleBean;
import com.wxtt.android.config.ConstantConfig;
import com.wxtt.android.realm.table.FavouriteRealm;
/**
 * 说明：收藏数据库操作
 * <p/>
 * 作者：fanly
 * <p/>
 * 时间：2016/2/16 18:47
 * <p/>
 * 版本：verson 1.0
 */
public class FavouriteRealmUtils {

    private final String REALM_NAME = ConstantConfig.REALM_NAME.FAVOURITE;
    private RealmUtils mRealmUtils;

    public FavouriteRealmUtils(Context context){
        mRealmUtils = RealmUtils.get(context,REALM_NAME);
    }

    /**
     * 说明：判断是否收藏
     * @param articleBean
     * @return
     */
    public boolean isFavourite(WxArticleBean articleBean){
        if (articleBean == null){
            return false;
        }
        return !mRealmUtils.findAll(FavouriteRealm.class,"id",articleBean.getId()).isEmpty();
    }

    /**
     * 说明：收藏文章
     * @param isCollection
     * @return true 操作成功，false 操作失败
     */
    public void favourite(boolean isCollection,WxArticleBean articleBean){
        FavouriteRealm favouriteTable = beanToTable(articleBean);
        if (favouriteTable == null){
            return;
        }
        if (isCollection){
            mRealmUtils.insert(favouriteTable);
        }else {
            mRealmUtils.delete(FavouriteRealm.class, "id", articleBean.getId());
        }
    }

    /**
     * 说明：将bean对象转table
     * @param bean
     * @return
     */
    private FavouriteRealm beanToTable(WxArticleBean bean){
        if (bean == null){
            return null;
        }
        FavouriteRealm table = new FavouriteRealm();
        table.setId(bean.getId());
        table.setFirstImg(bean.getFirstImg());
        table.setMark(bean.getMark());
        table.setSource(bean.getSource());
        table.setTitle(bean.getTitle());
        table.setUrl(bean.getUrl());
        table.setDate(DateUtils.getNowTime());
        return table;
    }

//    /**
//     * 说明：添加收藏
//     */
//    private void addCollection(FavouriteRealm realm){
//        RealmResults<FavouriteRealm> results = getResults(realm.getId());
//        if (results != null && !results.isEmpty()){
//            return;
//        }
//        mRealm.beginTransaction();
//        FavouriteRealm favouriteRealm = mRealm.copyToRealm(realm);
//        mRealm.commitTransaction();
//    }

//    /**
//     * 说明：取消收藏
//     */
//    private void deleteCollection(FavouriteRealm table){
//        RealmResults<FavouriteRealm> results = getResults(table.getId());
//        mRealm.beginTransaction();
//        if (results != null){
//            results.clear();
//        }
//        mRealm.commitTransaction();
//    }

//    private RealmResults<FavouriteRealm> getResults(String id){
//        return mRealm.where(FavouriteRealm.class)
//                .equalTo("id",id).findAll();
//    }

}
